<?php
/**
 * @file
 * 定义 Behavior_Serializefield 类
 */

/**
 * Behavior_Serializefield 序列化数据后存入对应数据库字段，使该字段能存储多种类型数据
 * @example:
 *  'behaviors_settings' => array
 *   (
 *     'serializefield' =>array(
 *       'fields' => 'property',
 *       'default_values' =>array(
 *           'property'=>array()
 *       ),
 *      ),
 */
class Model_Behavior_Serializefield extends QDB_ActiveRecord_Behavior_Abstract
{

    protected $_virtual_props=array();
    /**
     * 设置
     *
     * @var array
     */
    protected $_settings = array
    (
        //! 需要序列化处理的字段
        'fields'      => array(),
        //! 默认值
        'default_values' => array()
    );

    /**
     * 绑定插件
     */
    function bind()
    {
        $fields= Q::normalize($this->_settings['fields']);
        if (empty($fields)){
            return ;
        }
        foreach ($fields as $field){
            $this->_meta->setPropGetter($this->_meta->fields2props[$field],array($this,'getProp'));
            $this->_meta->setPropSetter($this->_meta->fields2props[$field],array($this,'setProp'));
        }
    }

    /**
     * 撤销绑定
     */
    function unbind()
    {
    	parent::unbind();
        $fields= Q::normalize($this->_settings['fields']);
        if (empty($fields)){
            return ;
        }
    	foreach ($fields as $field){
    	    $this->_meta->unsetPropGetter($this->_meta->fields2props[$field]);
    	    $this->_meta->unsetPropSetter($this->_meta->fields2props[$field]);
    	}
    }
    function getProp (QDB_ActiveRecord_Abstract $obj,$prop_name,$custom_params,$_props){
        if (strlen($_props[$prop_name])){
            return unserialize(preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $_props[$prop_name] ));
        }elseif (isset($this->_settings['defualt_values'][$prop_name])){
            return $this->_settings['defualt_values'][$prop_name];
        }else {
            return null;
        }
    }
    function setProp (QDB_ActiveRecord_Abstract $obj,$value,$prop_name,$custom_params,$_props){
    	$value=str_replace("\r",'',$value);	//取出 \r 字符-_-#
        if (!empty($value)){
            $_props[$prop_name]=serialize($value);
        }else {
            $_props[$prop_name]=null;
        }
        $obj->willChanged($prop_name);
        return $obj;
    }
}
